package chatRoom.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import chatRoom.network.Server;

public class ChatServer implements Server
{
	private final int				port;
	private ServerSocket			server;
	private List<Thread>			threads;
	private List<ChatConnection>	connections;
	private boolean					done	= false;

	public ChatServer(int i)
	{
		port = i;
		connections = new ArrayList<ChatConnection>();
		threads = new ArrayList<Thread>();
		try
		{
			server = new ServerSocket(port);
			server.setSoTimeout(1000);
			System.out.println("Server Started");
		}
		catch (IOException e)
		{
		}
	}

	public List<ChatConnection> getConnections()
	{
		return connections;
	}

	public int getPort()
	{
		return port;
	}

	public void run()
	{
		while (!done)
		{
			Socket sock;
			try
			{
				sock = server.accept();
				ChatConnection connection = new ChatConnection(sock);
				connections.add(connection);
				Thread temp = new Thread(connection);
				threads.add(temp);
				temp.start();
				System.out.println("Client connected.");
			}
			catch (IOException e)
			{
			}

			for (ChatConnection c : connections)
			{
				if (c.isTerminated())
				{
					int index = connections.indexOf(c);
					threads.get(index).interrupt();
					threads.remove(index);
					connections.remove(index);
				}
				else
				{
					LinkedList<String> input = c.getReceived();
					for (String s : input)
					{
						if (s.startsWith("PRIVMSG"))
						{
							int startChannel = s.indexOf(" ");
							System.out.println(startChannel);
							int endChannel = s.indexOf(" ", startChannel + 1);
							System.out.println(endChannel);

							String channel = s.substring(startChannel + 1, endChannel);
							String message = s.substring(endChannel + 1);

							System.out.println(message);
							sendMessageToChannel(c, channel, message);
						}
					}
				}
			}
		}
	}

	public void closeConnections()
	{
		for (Thread t : threads)
		{
			t.interrupt();
		}

		threads = new ArrayList<Thread>();
		connections = new ArrayList<ChatConnection>();
	}

	public ServerSocket getSocket()
	{
		return server;
	}

	private void sendMessageToChannel(ChatConnection c, String channel, String message)
	{
		for (ChatConnection cc : connections)
		{
			cc.sendToClient(message);
		}
	}
}
